import UserImformation.Account;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.lang.String;

@WebServlet("/LoginCheckServlet")
public class LoginCheckServlet extends HttpServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        doPost(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String user_name = req.getParameter("user_name");
        String password = req.getParameter("password1");
        String str = null;
        int exit = 0;

        File file = new File("UserInfo.txt");
        //判断该用户是否存在
        int n = 0;
        Reader reader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(reader);
        while ((str = bufferedReader.readLine()) != null) {
            if(!str.trim().equals("")){
                n++;
            }
        }
        bufferedReader.close();
        reader.close();
        int len = 0;
        Account[] users;
        if(n != 0) {
            users = new Account[n];
            Jsonb jsonb = JsonbBuilder.create();

            reader = new FileReader(file);
            bufferedReader = new BufferedReader(reader);
            while ((str = bufferedReader.readLine()) != null) {
                if (!str.trim().equals("")) {
                    users[len++] = jsonb.fromJson(str, Account.class);
                }
            }
            bufferedReader.close();
            reader.close();

            if (users != null) {
                for (int i = 0; i < users.length; i++) {
                    if (users[i].getUsername().equals(user_name)) {
                        if (users[i].getPassword().equals(password)) {
                            Account account = users[i];
                            Map<String, String> info = new HashMap<String, String>();
                            info.put("username", account.getUsername());
                            HttpSession session = req.getSession(true);
                            session.setAttribute("user", info);
                            account = users[i];
                            exit = 1;
                            break;
                        }
                        else {
                            exit = 2;
                            break;
                        }
                    }
                }
            }
        }

        String json = "{\"exit\":\"" + exit + "\"}";
        resp.setContentType("application/json, charset = utf-8");
        resp.getWriter().println(json);

    }
}
